<?php
class entry extends adminController {
    public $_indexView = "admin/entry/index";
    public $_listView = "admin/entry/list";
    public $_addView = "admin/entry/add";
    public $_editView = "admin/entry/edit";
    
	public function __construct() {
		parent::__construct ();
	}
	
    public function loadView($temp) {
        if (!isset($temp["data"]))
            $temp["data"] = '';
        $this->load->view("admin/index", $temp);
    }
    
    public function index() {
        $temp["template"] = $this->_listView;
        $temp["data"] = $this->entryModel->get();
        $this->loadView($temp);
    }
    
    public function add() {
        $temp["template"] = $this->_addView;
        if(!$this->isPost()) {
            $temp['categories'] =  $this->categoryModel->get_order_where(null, 'number', 'asc', array('parentid' => 0));
            $this->loadView($temp);
            return;   
        }
        $data = $this->input->post();
        $slug = mb_strtolower(url_title(removesign($data['title'])));
        if($this->entryModel->check_exist('slug', $slug)) {
            $slug = $slug.'-'.random_string('alnum', 4);
        }
        $data['slug'] = $slug;
        $account = $this->session->userdata('account');
        $data['accountid'] = $account['id'];
        $data['startdate'] = date('Y-m-d H:i:s');
        $this->entryModel->insert($data);
        $this->index();
    }
    
    public function edit($id) {
        $temp["template"] = $this->_editView;
        if(!$this->isPost()) {
            $temp['categories'] = $this->categoryModel->get_order_where(null, 'number', 'asc', array('parentid' => 0));
            $temp["data"] = $this->entryModel->read($id);
            $temp['parent'] = $this->getParent();
            $this->loadView($temp);
            return;   
        }
        $this->entryModel->update($this->input->post(), array('id' => $id));
        redirect(base_url().$this->_indexView);
    }
    
    public function delete($id) {
        $this->entryModel->delete($id);
        redirect(base_url().$this->_indexView);
    }
    
    public function getParent() {
        $result = array();
        $parent = $this->categoryModel->get_order_where(null, 'number', 'asc', array('parentid' => 0));
        $par = array();
        foreach($parent as $k=>$v) {
            $par[$v['id']] = $v['id'];
        }
        $categories = $this->categoryModel->get();
        foreach($categories as $k=>$v) {
            if($v['parentid'] != 0) {
                $result[$v['id']] = $par[$v['parentid']];
            }
        }
        return $result;
    }
}
?>